package io.renren.modules.app.service.impl;

import io.renren.common.utils.R;
import io.renren.modules.app.dao.ImFriendDao;
import io.renren.modules.app.dao.ImFriendTagDao;
import io.renren.modules.app.dao.ImTagDao;
import io.renren.modules.app.entity.ImFriendEntity;
import io.renren.modules.app.entity.ImFriendTagEntity;
import io.renren.modules.app.entity.ImTagEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.ImFriendService;
import io.renren.modules.app.utils.GB2Alpha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service("imFriendService")
public class ImFriendServiceImpl extends ServiceImpl<ImFriendDao, ImFriendEntity> implements ImFriendService {

    @Autowired
    ImFriendDao imFriendDao;
    @Autowired
    ImTagDao imTagDao;
    @Autowired
    ImFriendTagDao imFriendTagDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ImFriendEntity> page = this.page(
                new Query<ImFriendEntity>().getPage(params),
                new QueryWrapper<ImFriendEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Map<String, List<ImFriendEntity>> getListById(UserEntity user) {
        List<ImFriendEntity> list = imFriendDao.getListById(user);
        Map<String, List<ImFriendEntity>> map = new HashMap<>();
        //获取首字母  +++ 装到map里
        for (ImFriendEntity imf : list){
            imf.setZm(new GB2Alpha().String2Alpha(imf.getName()));
            // map是否包含此key，若已经包含则添加一个新的数字到对应value集合中
            if (map.containsKey(imf.getZm())){
                map.get(imf.getZm()).add(imf);
            }else{
                // map不包含此key，则重新创建一个新集合，并把这个数字添加进集合
                // ，再把集合放到map中
                List<ImFriendEntity> newList = new ArrayList<>();
                newList.add(imf);
                map.put(imf.getZm(), newList);
            }
        }
        //排序
        Set set=map.keySet();
        Object[] arr=set.toArray();
        Arrays.sort(arr);
        //key排序   获取value
        Map<String, List<ImFriendEntity>> map1 = new HashMap<>();
        for(Object key:arr){
            map1.put(key.toString(),map.get(key));
            System.out.println(key+": "+map.get(key));
        }
        return map1;
    }

    @Transactional
    @Override
    public R setremarktag(UserEntity user, UserEntity bean) {
        ImFriendEntity ifend = this.getOne(new QueryWrapper<ImFriendEntity>().eq("isblack", 0).eq("friend_id", bean.getUserId()).eq("user_id",user.getUserId()));
        if (ifend==null)return R.error("对方不存在或者已经把你拉黑");
        // 设置备注
        ifend.setNickname(bean.getNickname());
        this.baseMapper.updateById(ifend);
        //获取当前好友标签
        List<ImTagEntity> list = imTagDao.selectFriendList(bean.getUserId());
        // 获取当前用户所有标签
        List<ImTagEntity> tagList = imTagDao.selectList(new QueryWrapper<ImTagEntity>().eq("user_id",user.getUserId()));
        String [] tags = bean.getTags().split(",");
        ImTagEntity tagBean = new ImTagEntity();
        tagBean.setUserId(user.getUserId().intValue());
        tagBean.setCreatedAt(new Date());
        tagBean.setUpdatedAt(new Date());
        List<Integer>newIds = new ArrayList<>();//新增的ids 没用上
        List<Integer>oldIds = new ArrayList<>();//已有的ids
        for (String tag : tags){
            Boolean isHave = true;
            for (ImTagEntity it : tagList){
                if(tag.equals(it.getName())){
                    oldIds.add(it.getId());
                    isHave = false;
                    break;
                }
            }
            if(isHave){
                tagBean.setName(tag);
                imTagDao.insert(tagBean);
                ImFriendTagEntity ft = new ImFriendTagEntity();
                ft.setTagId(tagBean.getId());
                ft.setFriendId(bean.getUserId().intValue());
                ft.setCreatedAt(new Date());
                ft.setUpdatedAt(new Date());
                imFriendTagDao.insert(ft);
                newIds.add(tagBean.getId());
            }
        }
        //删除去掉的
        for(ImTagEntity it : list){
            Boolean isHave = true;
            for (Integer i : oldIds){
                if(i==it.getId()){
                    isHave=false;
                    break;
                }
            }
            if(isHave){
                imFriendTagDao.deleteById(it.getFtId());
            }
        }
        return R.ok();
    }

    @Override
    public R setstar(UserEntity user, ImFriendEntity bean) {
        ImFriendEntity ifend = this.getOne(new QueryWrapper<ImFriendEntity>().eq("isblack", 0).eq("friend_id", bean.getUserId()).eq("user_id",user.getUserId()));
        if (ifend==null)return R.error("对方不存在或者已经把你拉黑");
        // 设置/取消星标好友
        ifend.setStar(bean.getStar());
        this.baseMapper.updateById(ifend);
        return R.ok();
    }

    @Override
    public R setblack(UserEntity user, UserEntity bean) {
        ImFriendEntity ifend = this.getOne(new QueryWrapper<ImFriendEntity>().eq("friend_id", bean.getUserId()).eq("user_id",user.getUserId()));
        if (ifend==null)return R.error("对方不存在或者已经把你拉黑");
        // 设置/取消星标好友
        ifend.setIsblack(bean.getIsblack());
        this.baseMapper.updateById(ifend);
        return R.ok();
    }

    @Override
    public R setMomentAuth(UserEntity user, UserEntity bean) {
        ImFriendEntity ifend = this.getOne(new QueryWrapper<ImFriendEntity>().eq("isblack", 0).eq("friend_id", bean.getUserId()).eq("user_id",user.getUserId()));
        if (ifend==null)return R.error("对方不存在或者已经把你拉黑");
        // 设置/取消星标好友
        ifend.setLookhim(bean.getLookhim());
        ifend.setLookme(bean.getLookme());
        this.baseMapper.updateById(ifend);
        return R.ok();
    }

}
